<?php

class Custom_ConvertIsbn{

	public static function convertIsbn10to13($isbn){
		
		if(10 == strlen($isbn)){
			$isbn = "978" . substr($isbn, 0, -1);
			return self::genIsbn13CheckBit($isbn);
		}else{
			return self::genIsbn13CheckBit(substr($isbn, 0, -1));
		}
	
	}
	
	public static function genIsbn13CheckBit($isbn){
		$sumEven = $sumOdd = 0;
		for($i = 0; $i < 12; $i+=2){	
			$sumEven += substr($isbn, $i, 1);
			$sumOdd += substr($isbn, $i+1, 1) * 3;
		}
		$checkBit = ($sumEven + $sumOdd)%10;
		if(0 == $checkBit) {return ($isbn . $checkBit); } 
		$checkBit = (10 - $checkBit);
		return ($isbn . $checkBit);		
	}
	
	public static function convertIsbn13to10($isbn){
		
		if(13 == strlen($isbn)){
			if("978" == substr($isbn,0,3)){
				$isbn = substr($isbn, 3, -1);
				return self::genIsbn10CheckBit($isbn);
			}else{
				return null;
			}
		}else{
			return self::genIsbn10CheckBit($isbn);
		}
	}
	
	public static function genIsbn10CheckBit($isbn){
		$sum = 0;
		for ($i = 0; $i < 10; $i++){
			$sum += (substr($isbn, $i, 1) * ($i + 1));
		}
		$checkBit = $sum % 11;	
		if (10 == $checkBit) {return ($isbn . "X"); }
		return ($isbn . $checkBit); 
	}
}